package com.houdoudou.supplier.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;


import com.houdoudou.supplier.R;
import com.houdoudou.supplier.bean.Branch;
import com.houdoudou.supplier.bean.Sort;
import com.houdoudou.supplier.bean.Product;
import com.houdoudou.supplier.bean.Supplier;
import com.houdoudou.supplier.common.AsynImageLoader;
import com.houdoudou.supplier.common.CommonFunction;
import com.houdoudou.supplier.common.Constant;
import com.houdoudou.supplier.common.HorizontalListView;
import com.houdoudou.supplier.common.ListViewUtil;
import com.houdoudou.supplier.common.PicUtil;
import com.houdoudou.supplier.common.UpLoadPic;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ProductBasicFragment extends Fragment {
    
	
    TextView title;
	RadioGroup auth,type,cold,hot,normal;
	RadioButton  auth_yes,auth_no,type_yes,type_no,hot_yes,hot_no,cold_yes,cold_no,normal_yes,normal_no;
	EditText id,name,sale_num,detail;
	TextView result;
	View.OnClickListener myOnclickListener;	
	Button confirm,refresh_index,addBranch,addpic;
	RelativeLayout seeShadow;
	Spinner sp_index;
	ProgressBar progres;
	ListView listview_branch;
	HorizontalListView listview_pic;
	MyListAdapter myListAdapter;
	PicAdapter picListAdapter;
	JSONArray branchesJA= new JSONArray();
	ArrayAdapter<String> sort_adapter;
	int[] array_sort_id=new int[50]; //用于存目录的ID
	List<String> sp_sort_data= new ArrayList<String>();
	String uploadFile="",picType="",Pic_URL="";
	List<String> files= new ArrayList<String>();
	List<String> urls= new ArrayList<String>();
   
    List<Bitmap>  bitmaps= new ArrayList<Bitmap>();
	String affair="";
	JSONObject productJO= new JSONObject();
	AsynImageLoader imageLoader;
	String a;
	List<Boolean> seeProductFirstLoadPic= new  ArrayList<Boolean>();
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view= inflater.inflate(R.layout.frg_product_basic,container,false);
		imageLoader= new AsynImageLoader(getActivity());
		  init_listener();
          init_component(view);   
          assign();
          refresh_index.performClick();
		return view;
	}
	@Override
	public void setArguments(Bundle bundle) {
		// TODO Auto-generated method stub
		// super.setArguments(args);
		affair=bundle.getString("affair");
		if(affair.equals("updateProduct")||affair.equals("seeProduct")){
			productJO= JSONObject.fromObject(bundle.getString("product"));
			
		}
	}
  
	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
		if(!hidden){	
			assign();
		}
	}
	
	private void assign(){
		System.out.println("affair="+affair);
		System.out.println("productJO  "+ productJO.toString());
		if(affair.equals("createProduct")) {
			title.setText("新增产品");
			confirm.setText("确认新增");
			clear_all_infocomponet();
			enable_all_infocomponent();
			addBranch.performClick();	
			addpic.performClick();
			
		}
		else if(affair.equals("updateProduct")){
			title.setText("修改产品");
			confirm.setText("确认修改");
			assign_all_infocomponet();
			enable_all_infocomponent();
		}
		else if(affair.equals("seeProduct")){	
			title.setText("查看产品");
			assign_all_infocomponet();
		    disable_all_infocomponent();
		
		}
	} 
	
	private void init_component(View view){	
		title=(TextView) view.findViewById(R.id.tv_mainttitle_frg_product_basic);
		auth=(RadioGroup) view.findViewById(R.id.rg_isauthority_frg_product_basic);
		type=(RadioGroup) view.findViewById(R.id.rg_type_frg_product_basic);
		hot=(RadioGroup) view.findViewById(R.id.rg_hot_frg_product_basic);
		cold=(RadioGroup) view.findViewById(R.id.rg_cold_frg_product_basic);
		normal=(RadioGroup) view.findViewById(R.id.rg_normal_frg_product_basic);
		addBranch= (Button) view.findViewById(R.id.btn_addbranch_frg_product_basic);
		id=(EditText) view.findViewById(R.id.et_id_frg_product_basic);
		name=(EditText) view.findViewById(R.id.et_name_frg_product_basic);	
		sale_num=(EditText) view.findViewById(R.id.et_salenum_frg_product_basic);		
		detail=(EditText) view.findViewById(R.id.et_detail_frg_product_basic);
		sp_index=(Spinner) view.findViewById(R.id.sp_index_frg_product_basic);
		
		addpic=  (Button) view.findViewById(R.id.btn_addpic_frg_product_basic);
		
		 auth_yes=(RadioButton) view.findViewById(R.id.rb_authyes_frg_product_basic);
		 auth_no=(RadioButton) view.findViewById(R.id.rb_authno_frg_product_basic);
		 type_yes=(RadioButton) view.findViewById(R.id.rb_typeyes_frg_product_basic);
		 type_no=(RadioButton) view.findViewById(R.id.rb_typeno_frg_product_basic);
		 hot_yes=(RadioButton) view.findViewById(R.id.rb_hotyes_frg_product_basic);
		 hot_no=(RadioButton) view.findViewById(R.id.rb_hotno_frg_product_basic);
		 cold_yes=(RadioButton) view.findViewById(R.id.rb_coldyes_frg_product_basic);
		 cold_no=(RadioButton) view.findViewById(R.id.rb_coldno_frg_product_basic);
		 normal_yes=(RadioButton) view.findViewById(R.id.rb_normalyes_frg_product_basic);
		 normal_no=(RadioButton) view.findViewById(R.id.rb_normalno_frg_product_basic);
			
		 seeShadow= (RelativeLayout) view.findViewById(R.id.lt_seeshadow_frg_product_basic);
		 refresh_index=(Button) view.findViewById(R.id.btn_refreshindex_frg_product_basic);
		
		confirm=(Button) view.findViewById(R.id.btn_confirm_frg_product_basic);
	
		result=(TextView) view.findViewById(R.id.tv_functionresult_frg_product_basic);
		progres= (ProgressBar) view.findViewById(R.id.prgs_frg_product_basic);
		listview_pic= (HorizontalListView) view.findViewById(R.id.listview_pic_frg_product_basic);
		listview_branch=(ListView) view.findViewById(R.id.listview_branch_frg_product_basic);
		//////////////////////
	//	confirm.setEnabled(false);
		confirm.setOnClickListener(myOnclickListener);
		
		addpic.setOnClickListener(myOnclickListener);	
	//	pics.add(pic1);pics.add(pic2);pics.add(pic3);pics.add(pic4);pics.add(pic5);
		refresh_index.setOnClickListener(myOnclickListener);
	    addBranch.setOnClickListener(myOnclickListener);
		progres.setVisibility(View.INVISIBLE);
		
		////////////////////
		myListAdapter=new MyListAdapter(getActivity());
		listview_branch.setAdapter(myListAdapter);
		ListViewUtil.setListViewHeightBasedOnChildren(listview_branch);
		picListAdapter= new PicAdapter(getActivity());
		listview_pic.setAdapter(picListAdapter);
		/////////////////
		 
		
	}
	
	private void enable_all_infocomponent(){	
		auth.setClickable(true);				
		id.setClickable(false);	
		name.setClickable(true);	
		sale_num.setClickable(false);	
		detail.setClickable(true);	
		sp_index.setClickable(true);	    
		 auth_yes.setClickable(true);	
		 auth_no.setClickable(true);	
		 type_yes.setClickable(true);	
		 type_no.setClickable(true);	
		 cold_yes.setClickable(true);	
		 cold_no.setClickable(true);	
		 hot_yes.setClickable(true);	
		 hot_no.setClickable(true);	
		 normal_yes.setClickable(true);	
		 normal_no.setClickable(true);		 
		 confirm.setVisibility(View.VISIBLE);
		 addBranch.setVisibility(View.VISIBLE);
		 addpic.setVisibility(View.VISIBLE);
		 refresh_index.setVisibility(View.VISIBLE);
		 id.setFocusable(false);
		 sale_num.setFocusable(false);
	     seeShadow.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
	}
	private void disable_all_infocomponent(){	
		seeShadow.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
		auth.setClickable(false);				
		id.setClickable(false);
		name.setClickable(false);
		sale_num.setClickable(false);	
		detail.setClickable(false);
		sp_index.setClickable(false);    
		 auth_yes.setClickable(false);
		 auth_no.setClickable(false);	
		 type_yes.setClickable(false);
		 type_no.setClickable(false);	
		 cold_yes.setClickable(false);
		 cold_no.setClickable(false);	
		 hot_yes.setClickable(false);
		 hot_no.setClickable(false);	
		 normal_yes.setClickable(false);
		 normal_no.setClickable(false);		 
		 confirm.setVisibility(View.INVISIBLE);
		 addBranch.setVisibility(View.INVISIBLE);
		 addpic.setVisibility(View.INVISIBLE);
		 refresh_index.setVisibility(View.INVISIBLE);
		 id.setFocusable(false);
		 sale_num.setFocusable(false);
		
	}
	private void clear_all_infocomponet(){
	  
		result.setText("");
		auth.clearCheck();	
		id.setText("");
		name.setText("");
		sale_num.setText("");	
		detail.setText("");
		sp_index.setSelection(0);
	    type.clearCheck();
		normal.clearCheck();
		hot.clearCheck();
		cold.clearCheck();
	    files.clear();
		 picListAdapter.notifyDataSetChanged();
		branchesJA.clear();
		myListAdapter.notifyDataSetChanged();
		
	}
	private void assign_all_infocomponet(){
		result.setText("");
		id.setText(productJO.getInt(Product.ID)+"");
		name.setText(productJO.getString(Product.NAME));
		sale_num.setText(productJO.getInt(Product.SALE)+"");	
		int sortID= productJO.getInt(Product.SORT);
		for(int i=0 ;i<array_sort_id.length;i++){
			if(sortID==array_sort_id[i]){
			sp_index.setSelection(i, true); break;
			}
		}
		if(productJO.getInt(Product.ISAUTH)==1){ auth.check(R.id.rb_authyes_frg_product_basic);}
		if(productJO.getInt(Product.ISAUTH)==2){ auth.check(R.id.rb_authno_frg_product_basic);}
		
		if(productJO.getInt(Product.TYPE)==1){ type.check(R.id.rb_typeyes_frg_product_basic);}
		if(productJO.getInt(Product.TYPE)==2){ type.check(R.id.rb_typeno_frg_product_basic);}
		
		if(productJO.getInt(Product.ISHOT)==1){  hot.check(R.id.rb_hotyes_frg_product_basic);}
		if(productJO.getInt(Product.ISHOT)==2){ hot.check(R.id.rb_hotno_frg_product_basic);}
		
		if(productJO.getInt(Product.ISCOLD)==1){ cold.check(R.id.rb_coldyes_frg_product_basic);}
		if(productJO.getInt(Product.ISCOLD)==2){ cold.check(R.id.rb_coldno_frg_product_basic);}
		
		if(productJO.getInt(Product.ISNORMAL)==1){ normal.check(R.id.rb_normalyes_frg_product_basic);}
		if(productJO.getInt(Product.ISNORMAL)==2){ normal.check(R.id.rb_normalno_frg_product_basic);}
		
		detail.setText(productJO.getString(Product.DETAIL));
	 
		branchesJA= productJO.getJSONArray("branches");
		myListAdapter.notifyDataSetChanged();
		
		files.clear(); bitmaps.clear();
		seeProductFirstLoadPic.clear();
		for(int i=0 ;i<productJO.getInt(Product.PICNUM);i++){
			files.add(""); bitmaps.add(null);
			seeProductFirstLoadPic.add(true);	
		}
		picListAdapter.notifyDataSetChanged();
		picListAdapter.notifyDataSetChanged();
		picListAdapter.notifyDataSetChanged();

		
	}
	
	private void init_listener(){
		
	/////////////////////////////////////////////////////////////////
		
		myOnclickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(v==confirm) {
				result.setText("");	 
			     if(affair.equals("updateProduct")){
			    	 int Product_ID=Integer.parseInt(id.getText().toString());
	                  productJO.put(Product.ID,Product_ID);	  }
			     
			     if(affair.equals("createProduct")||affair.equals("updateProduct")){ 	    	 
				if( name.getText().toString().length()>8){ alert("输入错误提示", "名称不能超过8个字");return;	} 
				productJO.put(Product.NAME, name.getText().toString());  
			  											 
				int sp_index_position=sp_index.getSelectedItemPosition(); 
				if(sp_index_position==-1) { alert("输入错误提示", "分类未选择"); return; }		
				 productJO.put(Product.SORT, array_sort_id[sp_index_position]);
				 
				if(auth.getCheckedRadioButtonId()==R.id.rb_authyes_frg_product_basic) {productJO.put(Product.ISAUTH, 1);}
				else if(auth.getCheckedRadioButtonId()==R.id.rb_authno_frg_product_basic){productJO.put(Product.ISAUTH, 2);}
				else if(auth.getCheckedRadioButtonId()==-1){ alert("输入错误提示", "上架未选择"); return;        } 
				
				 productJO.put(Product.OWNER, Constant.supplierJO.get(Supplier.OWNER));
				 productJO.put(Product.SUPPLIER, Constant.supplierJO.get(Supplier.TELNUM));
				 
               
				if( detail.getText().toString().length()>200){alert("输入错误提示", "描述不能超过200个字");  return;	}
					productJO.put(Product.DETAIL, detail.getText().toString());
					
				if(type.getCheckedRadioButtonId()==-1) { alert("输入错误提示", "产品类型未选择"); return; }
				else if(type.getCheckedRadioButtonId()==R.id.rb_typeno_frg_product_basic){  productJO.put(Product.TYPE, 2);}
				else if(type.getCheckedRadioButtonId()==R.id.rb_typeyes_frg_product_basic){  productJO.put(Product.TYPE, 1);   } 
				
				if(hot.getCheckedRadioButtonId()==-1) { alert("输入错误提示", "能否加热未选择"); return; }
				else if(hot.getCheckedRadioButtonId()==R.id.rb_hotno_frg_product_basic){  productJO.put(Product.ISHOT, 2);}
				else if(hot.getCheckedRadioButtonId()==R.id.rb_hotyes_frg_product_basic){  productJO.put(Product.ISHOT, 1);   } 
				
				if(cold.getCheckedRadioButtonId()==-1) { alert("输入错误提示", "能否制冷未选择"); return; }
				else if(cold.getCheckedRadioButtonId()==R.id.rb_coldno_frg_product_basic){  productJO.put(Product.ISCOLD, 2);}
				else if(cold.getCheckedRadioButtonId()==R.id.rb_coldyes_frg_product_basic){  productJO.put(Product.ISCOLD, 1);   } 
				
				if(normal.getCheckedRadioButtonId()==-1) { alert("输入错误提示", "能否不加热也不制冷未选择"); return; }
				else if(normal.getCheckedRadioButtonId()==R.id.rb_normalno_frg_product_basic){  productJO.put(Product.ISNORMAL, 2);}
				else if(normal.getCheckedRadioButtonId()==R.id.rb_normalyes_frg_product_basic){  productJO.put(Product.ISNORMAL, 1);   } 
				
				for(int i=0;i<files.size();i++){
					if(files.get(i).isEmpty()){alert("输入错误提示", "第"+i+"张图片，没有选择，请选择图片，或者删除"); return; }
				}
				productJO.put(Product.PICNUM, files.size());
				
				for(int i=0; i<branchesJA.size();i++){
					branchesJA.getJSONObject(i).put(Branch.ID, i);	
					int nameLenth=branchesJA.getJSONObject(i).getString(Branch.NAME).length();
					if(nameLenth>10||nameLenth<=0){ alert("输入错误提示", "第"+i+"行子配置有误，名称不能超过10个字,也不能为空"); return; }
				    double priceValue=branchesJA.getJSONObject(i).getDouble(Branch.PRICE);
				    if(priceValue<=0){ alert("输入错误提示", "第"+i+"行子配置有误，价格必须大于0"); return; }
					int volumeValue=branchesJA.getJSONObject(i).getInt(Branch.VOLUME);
					 if(volumeValue<=0||volumeValue>100){ alert("输入错误提示", "第"+i+"行子配置有误，空间必须大于0，小于100"); return; }
				    if(branchesJA.getJSONObject(i).getInt(Branch.ISAUTH)==0){ alert("输入错误提示", "第"+i+"行子配置有误，上架未选择"); return; }
					 
				}
				productJO.put("branches", branchesJA);
			
		               }			
				
				    result.setText("请稍后");
				    progres.setVisibility(View.VISIBLE);
					confirm.setEnabled(false);
					String[] params= new String[3];
	   	            params[0]=Constant.BaseUrl+Constant.SupplierUrl;
	                params[1]=affair; //PostCode
	                params[2]=productJO.toString();
	                new HttpPostTaskforProductBasic().execute(params);
				
				
			}// end of confirm
				
		
			if(v==addpic){
				files.add("");
				bitmaps.add(null);
				seeProductFirstLoadPic.add(false);
				picListAdapter.notifyDataSetChanged();
			}
			
            if(v==refresh_index){
            	
           
            	String[] params= new String[3];
   	            params[0]=Constant.BaseUrl+Constant.SupplierUrl;
                params[1]="searchIndex"; //PostCode
                JSONObject indexJO= new JSONObject();
                indexJO.put(Sort.SUPPLIER, Constant.supplierJO.getString(Supplier.TELNUM));
                params[2]=indexJO.toString();
                new HttpPostTaskforProductBasic().execute(params);
                
                
			}// end of refresh_index
            if(v==addBranch){
			   branchesJA.add(Branch.getEmptyJO());
				myListAdapter.notifyDataSetChanged();
				ListViewUtil.setListViewHeightBasedOnChildren(listview_branch);
			}// end of addBranch
        
            
			} //onclick()	
		};		
	}
	
	
	
	private  class HttpPostTaskforProductBasic extends android.os.AsyncTask<String,String,Map<String,Object>>{

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			  Map<String,Object> map =	CommonFunction.UniversalHttpPost(params);		             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
			// TODO Auto-generated method stub
		  //	super.onPostExecute(result);
			confirm.setEnabled(true);
			result.setText("");
			 progres.setVisibility(View.INVISIBLE);
			 String PostResult=(String) map.get("PostResult");
			 String affairOnPost="";
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				  result.setText("提示:网络故障或者网络配置有误，无法连接到服务器");
			      return;
			}
				Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean ActionStatus=false;
				String ErrorInfo="";
				JSONObject json = null;
				try{
			     json= JSONObject.fromObject(PostResult);
				 ActionStatus=json.getBoolean("success");
				 ErrorInfo=json.getString("errorInfo");	
				 affairOnPost=json.getString("affair");
				}catch(JSONException e){
					ErrorInfo="JSON解析错误"; 
				}
				 result.setText("提示:"+ErrorInfo);
				 if(! ActionStatus){  return ;}
				 
           if(affairOnPost.equals("createProduct")||affairOnPost.equals("updateProduct")){
			   if(ActionStatus){ 
				   id.setText(String.valueOf(json.getJSONObject("product").getInt(Product.ID)));
				 //  pic_url.setText(json.getString("Product_PicDir"));
				     String  baseUrl=json.getJSONObject("product").getString(Product.DIR);
				    //  uploadPic();
				     urls.clear();
				    for(int i=0 ;i<files.size();i++){
				    	urls.add(baseUrl+i+".jpg"); 
				    }
				     String[] nouse= new String[2]; 
				     new HttpPostTaskforUploadPic().execute( nouse);
				
			   }
			           		}
        
		   // 初始化sp_index
           if(affairOnPost.equals("searchIndex")){
        	   sp_sort_data.clear();
				JSONArray sorts= json.getJSONArray("sorts");		
				for (int i = 0; i < sorts.size(); i++) {
					sp_sort_data.add(sorts.getJSONObject(i).getString(Sort.NAME));
					array_sort_id[i]=sorts.getJSONObject(i).getInt(Sort.ID);					
				             }
				sort_adapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,sp_sort_data);
				sp_index.setAdapter(sort_adapter);
              	
				
	          	}// case 8
		
			}//onPostExecute
		
		}  //AsyncTask 



	class MyListAdapter extends BaseAdapter {
		   
		    private LayoutInflater layoutInflater;  
		    private Context context;  
		    
		public MyListAdapter(Context context) {
				super();					
				this.context = context;
			    this.layoutInflater=LayoutInflater.from(context); 
			}
		
		
		final class Zujian{  
		    public EditText price,name,volume;  
	        public Button del,up,down;  
	        public  RadioGroup isauth;
	        public  RadioButton authyes,authno;
	      //  public RadioButton auth_yes,auth_no;
	   }   //end of Zujian

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			 return branchesJA.size();  
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			 return branchesJA.getJSONObject(position);  
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position; 
		}
	 
		@Override
		public View getView(int position, View  convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int selectID = position;   
		      Zujian zujian=null;  
		        if(convertView==null){  
		            zujian=new Zujian();  
		            //获得组件，实例化组件  
		            convertView=layoutInflater.inflate(R.layout.list_product_basic, null);  
		          
		            zujian.price=(EditText) convertView.findViewById(R.id.et_price_list_product_basic);
		            zujian.name=(EditText) convertView.findViewById(R.id.et_name_list_product_basic); 
		            zujian.volume=(EditText) convertView.findViewById(R.id.et_volume_list_product_basic); 
		            zujian.isauth=  (RadioGroup) convertView.findViewById(R.id.rg_auth_list_product_basic);
		            zujian.del= (Button) convertView.findViewById(R.id.btn_pull_list_product_basic);     
		            zujian.authno=  (RadioButton) convertView.findViewById(R.id.rb_authno_list_product_basic); 
		            zujian.authyes=  (RadioButton) convertView.findViewById(R.id.rb_authyes_list_product_basic); 
		            convertView.setTag(zujian);  
		            System.out.println("position----"+position+"------inflated");
		        }else{   System.out.println("position----"+position+"-------not inflated");
		            zujian=(Zujian)convertView.getTag();  
		        }  
		        //绑定数据  
		        zujian.price.setText(branchesJA.getJSONObject(position).get(Branch.PRICE).toString());
		        zujian.volume.setText(branchesJA.getJSONObject(position).get(Branch.VOLUME).toString());
		        zujian.name.setText( branchesJA.getJSONObject(position).get(Branch.NAME).toString());
		        
		        int Branch_isAuthority= branchesJA.getJSONObject(position).getInt(Branch.ISAUTH);
		        if(Branch_isAuthority==1){ zujian.isauth.check(R.id.rb_authyes_list_product_basic);
		        }else if(Branch_isAuthority==2) { zujian.isauth.check(R.id.rb_authno_list_product_basic); }
		           if(affair.equals("seeProduct")){ zujian.authno.setClickable(false);  zujian.authyes.setClickable(false); }else{zujian.authno.setClickable(true);zujian.authyes.setClickable(true);}
		           if(affair.equals("seeProduct")){zujian.del.setVisibility(View.INVISIBLE); }else{zujian.del.setVisibility(View.VISIBLE);}		     
		        zujian.del.setOnClickListener(new View.OnClickListener() {					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						branchesJA.remove(selectID);
						myListAdapter.notifyDataSetChanged();
						ListViewUtil.setListViewHeightBasedOnChildren(listview_branch);
					}
				});     		    
		        
		      
		        
		        zujian.isauth.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						if(checkedId==R.id.rb_authyes_list_product_basic){branchesJA.getJSONObject(selectID).put(Branch.ISAUTH,1);}
						if(checkedId==R.id.rb_authno_list_product_basic){branchesJA.getJSONObject(selectID).put(Branch.ISAUTH,2); }	
					
					}
				});
		        zujian.name.setOnFocusChangeListener( new View.OnFocusChangeListener() {		
					@Override
					public void onFocusChange(View v, boolean hasFocus) {	
						if(!hasFocus){
							EditText name= (EditText)v;	
							branchesJA.getJSONObject(selectID).put(Branch.NAME,name.getText().toString());						
						}				
					}
				});
		        zujian.price.setOnFocusChangeListener( new View.OnFocusChangeListener() {		
					@Override
					public void onFocusChange(View v, boolean hasFocus) {	
						if(!hasFocus){
							EditText price= (EditText)v;	
							double priceValue=0;	
						    try{	 priceValue=Double.parseDouble(price.getText().toString());
						    branchesJA.getJSONObject(selectID).put(Branch.PRICE,priceValue);
						    }catch(Exception e){ return;}		   		
						}				
					}
				});
		       
		        zujian.volume.setOnFocusChangeListener( new View.OnFocusChangeListener() {		
					@Override
					public void onFocusChange(View v, boolean hasFocus) {	
						if(!hasFocus){
							EditText volume= (EditText)v;
							int volumeValue=0;
						    try{	volumeValue=Integer.parseInt(volume.getText().toString()); 
						    branchesJA.getJSONObject(selectID).put(Branch.VOLUME,volumeValue);		
						    }catch(Exception e){ return;}
						    
						    			
						}				
					}
				}); 
		        return convertView;
	           } 
	      }// end Adapter
	
	
	class PicAdapter extends BaseAdapter {
		   
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    
	public PicAdapter(Context context) {
			super();					
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		}
	
	
	final class Zujian{  
	   
        public Button del;  
        ImageView pic;
      //  public RadioButton auth_yes,auth_no;
   }   //end of Zujian

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		 return files.size();  
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		 return files.get(position);  
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position; 
	}
 
	@Override
	public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int selectID = position;   
	      Zujian zujian=null;  
	        if(convertView==null){  
	            zujian=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_pic_frg_product_basic, null);               
	            zujian.del= (Button) convertView.findViewById(R.id.btn_del_piclist_frg_product_basic);     
	            zujian.pic= (ImageView) convertView.findViewById(R.id.img_pic_piclist_frg_product_basic);  
	           
	            convertView.setTag(zujian);  
	            System.out.println("position----"+position+"------inflated");
	        }else{   System.out.println("position----"+position+"-------not inflated");
	            zujian=(Zujian)convertView.getTag();  
	        }  
	        //绑定数据  ,分情况
	        if(affair.equals("seeProduct")) {
	        	zujian.del.setVisibility(View.GONE);
	        	imageLoader.showImageAsyn(zujian.pic, productJO.getString(Product.DIR)+selectID+".jpg", R.drawable.tp_backgroud_1);
	        	 return convertView;      	
	        }
	        if(affair.equals("updateProduct")){        	
	        	if(seeProductFirstLoadPic.get(selectID)){
	        		files.set(selectID, context.getDir("productImages",Context.MODE_PRIVATE ).getAbsolutePath()+"/"+selectID+".jpg");
	        		seeProductFirstLoadPic.set(selectID,false);  
	        		imageLoader.showImageAsyn(zujian.pic, productJO.getString(Product.DIR)+selectID+".jpg", R.drawable.tp_backgroud_1);
	             }else{
	            	 if(!files.get(selectID).isEmpty()){
	       	    	  Bitmap bitmap=PicUtil.getLoacalBitmap(files.get(selectID));
	       	                  if(bitmap!=null){zujian.pic.setImageBitmap(bitmap);}
	       	    	    }
	             }
	        	
	        }
	       if( affair.equals("createProduct")){
	    	   if(!files.get(selectID).isEmpty()){
	       	    	  Bitmap bitmap=PicUtil.getLoacalBitmap(files.get(selectID));
	       	                  if(bitmap!=null){zujian.pic.setImageBitmap(bitmap);}
	       	    	    } 
	       }
	    	//  if(bitmaps.get(selectID)!=null){zujian.pic.setImageBitmap(bitmaps.get(selectID));}
	    	 
	       zujian.pic.setOnClickListener(new View.OnClickListener() {					
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					 Intent intent = new Intent();
		              intent.setType("image/*");
		              intent.setAction(Intent.ACTION_GET_CONTENT);
		              startActivityForResult(intent, selectID);
		              System.out.println(" before choose pic  requestCode="+ selectID);
				}
			});   
	       if(affair.equals("seeProduct")){zujian.del.setVisibility(View.INVISIBLE); }else{zujian.del.setVisibility(View.VISIBLE);}		     
	        zujian.del.setOnClickListener(new View.OnClickListener() {					
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					files.remove(selectID);
					bitmaps.remove(selectID);				
					picListAdapter.notifyDataSetChanged();
				
				}
			});     		    
	  
	       
	      
	        
	        return convertView;
           } 
      }// end Adapter
	
	
	
	
private  class HttpPostTaskforUploadPic extends android.os.AsyncTask<String,String,Map<String,Object>>{

	

	@Override
	protected Map<String,Object> doInBackground(String... params) {
		// TODO Auto-generated method stub
		//Map<String,Object> result=UpLoadPic.uploadFile(params[0],params[1]);
		Map<String,Object> result=UpLoadPic.uploadManyFiles(files,urls);
		return result;
	}

	@Override
	protected void onPostExecute(Map<String,Object> resultinfo) {
	
			 result.setText( result.getText().toString()+"\r\n上传图片：\r\n"+resultinfo.get("ErrorInfo").toString());	
	}	

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
	// TODO Auto-generated method stub
	
	
	 if (resultCode == Activity.RESULT_OK) {
         /**
          * 当选择的图片不为空的话，在获取到图片的途径
          */
         Uri uri = data.getData();
         Log.e("choose-tp", "uri = " + uri);
         try {
             String[] pojo = { MediaStore.Images.Media.DATA };

             Cursor cursor = getActivity().managedQuery(uri, pojo, null, null, null);
             if (cursor != null) {
                 ContentResolver cr = getActivity().getContentResolver();
                 int colunm_index = cursor
                         .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                 cursor.moveToFirst();
                 String path = cursor.getString(colunm_index);
                 /***
                  * 这里加这样一个判断主要是为了第三方的软件选择，比如：使用第三方的文件管理器的话，你选择的文件就不一定是图片了，
                  * 这样的话，我们判断文件的后缀名 如果是图片格式的话，那么才可以
                  */
                 if (path.endsWith("jpg") || path.endsWith("png")) {
                     uploadFile = path;
                     picType= path.substring(path.lastIndexOf(".")+1);
                     Log.e("choose-tp", "path = " + path+"------picType="+picType);
                 //    mText1.setText(uploadFile);
                     
                     Bitmap bitmap = BitmapFactory.decodeStream(cr
                             .openInputStream(uri));
                     bitmaps.set(requestCode, bitmap);
                     System.out.println(" after choose pic  requestCode="+ requestCode);               	
                     files.set(requestCode,path);  
                     picListAdapter.notifyDataSetChanged();
                    	picListAdapter.notifyDataSetChanged();
                  	 picListAdapter.notifyDataSetChanged();
                    // current_pic=bitmap;
                 } else {
                     alert("提示图片错误","只能加载jpg,png类型图片");
                 }
             } else {
                 alert("提示图片错误","没找到图片");
             }

         } catch (Exception e) {
         }
     }

     super.onActivityResult(requestCode, resultCode, data);
}	
private void alert(String title,String message) {
    Dialog dialog = new AlertDialog.Builder(getActivity()).setTitle(title)
            .setMessage(message)
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                   
                }
            }).create();
    dialog.show();
}


}

/*
 * 
 
   zujian.name.setOnFocusChangeListener( new View.OnFocusChangeListener() {		
					@Override
					public void onFocusChange(View v, boolean hasFocus) {	
						if(!hasFocus){
							EditText name= (EditText)v;	
							if(name.getText().toString().isEmpty()){  alert("输入错误，第",selectID+"行子配置，名称输入有误，不能为空，不能超过10个字"); return; }
							branchesJA.getJSONObject(selectID).put(Branch.NAME,name.getText().toString());						
						}				
					}
				});
		        zujian.price.setOnFocusChangeListener( new View.OnFocusChangeListener() {		
					@Override
					public void onFocusChange(View v, boolean hasFocus) {	
						if(!hasFocus){
							EditText price= (EditText)v;	
							double priceValue=0;
						    try{	 priceValue=Double.parseDouble(price.getText().toString());
						    }catch(Exception e){ alert("输入错误，第",selectID+"行子配置，价格输入有误"); return;}
							if(priceValue<=0){ alert("输入错误，第",selectID+"行子配置，价格要大于0"); return;}
						    branchesJA.getJSONObject(selectID).put(Branch.PRICE,priceValue);		
						}				
					}
				});
		       
		        zujian.volume.setOnFocusChangeListener( new View.OnFocusChangeListener() {		
					@Override
					public void onFocusChange(View v, boolean hasFocus) {	
						if(!hasFocus){
							EditText volume= (EditText)v;
							int volumeValue=0;
						    try{	volumeValue=Integer.parseInt(volume.getText().toString());      	
						    }catch(Exception e){ alert("输入错误","，第"+selectID+"行子配置，空间输入有误"); return;}
						    if(volumeValue<=0||volumeValue>100){ alert("输入错误，第",selectID+"行子配置，空间必须大于0,小于100"); return;}
						    branchesJA.getJSONObject(selectID).put(Branch.VOLUME,volumeValue);					
						}				
					}
				}); 
  
 * */
